package com.acwing.partition10;

import java.io.*;
import java.util.ArrayDeque;
import java.util.Queue;

/**
 * @author `RKC`
 * @date 2021/11/29 17:37
 */
@SuppressWarnings("all")
public class AC901滑雪 {

    private static final int[][] dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
    private static final int N = 310;
    private static int[][] g = new int[N][N], din = new int[N][N];
    private static Queue<int[]> q = new ArrayDeque<>(N * N);
    private static int n, m;

    private static StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    private static PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        n = nextInt(); m = nextInt();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                g[i][j] = nextInt();
            }
        }
        writer.println(topsort());
        writer.flush();
    }

    private static int topsort() {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                for (int[] dir : dirs) {
                    int nx = dir[0] + i, ny = dir[1] + j;
                    if (nx < 0 || nx >= n || ny < 0 || ny >= m || g[nx][ny] <= g[i][j]) continue;
                    din[i][j]++;
                }
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (din[i][j] == 0) {
                    q.add(new int[]{i, j});
                }
            }
        }
        int ans = 0;
        while (!q.isEmpty()) {
            ans++;
            int size = q.size();
            for (int i = 0; i < size; i++) {
                int[] cur = q.poll();
                int x = cur[0], y = cur[1];
                for (int[] dir : dirs) {
                    int nx = dir[0] + x, ny = dir[1] + y;
                    if (nx < 0 || nx >= n || ny < 0 || ny >= m || g[nx][ny] >= g[x][y]) continue;
                    if (--din[nx][ny] == 0) q.add(new int[]{nx, ny});
                }
            }
        }
        return ans;
    }

    private static int nextInt() throws IOException {
        tokenizer.nextToken();
        return (int) tokenizer.nval;
    }
}
